/*  
 * cafe-timeine.js
 * @Author :      GUORUI
 * @CreateDate :  2017年8月14日
 * Copyright (c) 2017, NRIET.　
 * 时间轴控件
 */

;define(function(){
	//获取时间数组
	function getTimeArr(curDate,timeInterval, cfg){
		var timeArr = [];
		var skTime = new Date(curDate);
		var maxtime = new Date(cfg.curDate);
		maxtime.setMinutes(skTime.getMinutes() + cfg.maxHour * 60);
		var isgt24h = timeInterval/60 >= 24;
		isgt24h = false;
		var isgt72h = false;
		//skTime.setMinutes(Math.floor(skTime.getMinutes() / timeInterval) * timeInterval);
		debugger
		var isHaveOldDate = $(".cafe-layer-body").find(".cafe-layer-item.active").attr("title"),isMatchDate = false;  //判断是否存在上一次点击的时间点
		if(!isHaveOldDate && $(".cafe-layer-body .cafe-layer-item").length !=0){
			isHaveOldDate = $(".cafe-tl-content .cafe-tl-item.active").attr("title");
		}
		var i = -1,dateIndex = -1;
		while(skTime.getTime() <= maxtime.getTime()){   //循环所有的时间点
			i++;
			if ((skTime.getTime() - new Date(cfg.curDate).getTime()) / 3600000 >= (cfg.splitPoint || 72)) 
				isgt72h = true;
			else
				isgt72h = false;
            timeArr.push({
				fullTime : isgt24h ? skTime.format("yyyy-MM-dd 00:00") : skTime.format("yyyy-MM-dd hh:mm"),
				isgt24h : isgt24h,
				showTime : skTime.format("hh:mm"),
				type : "def",
				isdef : isHaveOldDate?isHaveOldDate === fullTime :i===0
			});
            if(cfg.pro&&cfg.pro.ele&&cfg.pro.ele.type == "special" && ['TP1H','TMP'].indexOf(cfg.pro.ele.ele_id) != -1){
				skTime.setMinutes(skTime.getMinutes() + (Math.abs(timeInterval /60) == 1 && isgt72h ? timeInterval*6 : timeInterval));
			}else{
				skTime.setMinutes(skTime.getMinutes() + (Math.abs(timeInterval /60) == 3 && isgt72h ? timeInterval*2 : timeInterval));
			}
			
			if (skTime.getTime() > maxtime.getTime()) break;    //如果实况时间大于最大时间，跳出
			var fullTime = isgt24h ? skTime.format("yyyy-MM-dd 00:00") : skTime.format("yyyy-MM-dd hh:mm");
			if(isHaveOldDate && isHaveOldDate === fullTime){     //存在上次点击的时间点
				dateIndex = i;
				isMatchDate = true;
			}	
			if(timeInterval < 0 && i === timeBtnNum)     //如果时间间隔为负数，并且已经循环最大次数，跳出
				break;
		}
		if(!isMatchDate){      //如果不存在上次点击的点，就去第一个点，截取最大次数的数组
			timeArr[1].isdef = true;
            timeArr[0].isdef = false;
			timeArr.splice(timeBtnNum);
		}else{
			var startEndIndex = getTimeIndexRange(dateIndex,timeBtnNum,timeArr.length);    //否则，判断出上次点击的点，在哪个区间，截取时间集合
			timeArr = timeArr.slice(startEndIndex[0],startEndIndex[1]+1);
		}
		if(cfg.iszcqfx){
			timeArr.map(item=>{
				item.isdef = false;
			})
			//timeArr[0].isdef = true;
		}
		return timeArr;
	}
	function getTimeIndexRange(index,splitNum,totalTimeLength){
		var totalPage = Math.ceil(totalTimeLength/splitNum);
		for(var i=0;i<totalPage;i++){
			if(i*splitNum<=index && (i+1)*splitNum>index){
				if(totalTimeLength<=(i+1)*splitNum){
					return [i*splitNum,totalTimeLength-1]
				}
				return [i*splitNum,(i+1)*splitNum-1]
			}
		}
	}
	//创建主界面
	function bulidHtml(cfg){
		var $warp = $('<div>');
		$warp.addClass("cafe-timeline");
		if(1 == cfg.type){
			style1($warp,cfg);
		}else if(2 == cfg.type){
            style2($warp,cfg);
		}
		return $warp;
	}
	function style1($warp,cfg){
		var timeArr = getTimeArr(cfg.curDate,cfg.timeInterval, cfg);
		var $tip = $('<div>');
		$tip.addClass("cafe-tl-tip style1");
		bulidTip1($tip,timeArr);
		var $time = $('<div>');
		$time.addClass("cafe-tl-time style1");
		bulidTime1($time,timeArr,cfg);
		$warp.append($tip).append($time);
		return $warp;
	}
    function style2($warp,cfg){
        var timeArr = getTimeArr(cfg.curDate,cfg.timeInterval, cfg);
        var $time = $('<div>');
        $time.addClass("cafe-tl-time style1");
        bulidTime2($time,timeArr);
        $warp.append($time);
        return $warp;
    }
	function bulidTip1($tip){
		var $duration = $('<div>');
		$duration.addClass("cafe-tl-duration");
		var $lock = $('<div>');
		$lock.addClass("cafe-tl-lock active").append($('<i>'));
		var $hideBtn = $('<div>')
		$hideBtn.addClass("cafe-tl-hidebtn").append($('<i>').addClass("cafe-ifont cafe-ic-xiangzuoutotheleft"));
		$tip.append($duration).append($lock).append($hideBtn);
	}
	//创建时间轴界面
	function bulidTime1($time,timeArr,cfg){
		var $scroll = bulidScroll(timeArr);
		var $smooth = $('<section>').addClass("cafe-tl-smooth");
		var $sts = $('<div>').addClass("cafe-tl-sts");
		var $tsel = $('<div>').addClass("cafe-tl-sts-tselect");
		var $tlabel = $('<div>').addClass("cafe-tl-sts-tlabel");
		$tlabel.append($('<span>').addClass("cafe-tl-sts-tl-icon"));
		switch(parseInt(cfg.timeInterval)){
			//当时间间隔为5或6分钟或10分钟时，默认1小时
			case 5:
			case 6:
			case 10:
				$tlabel.append($('<span>').attr("tmid",1).addClass("cafe-tl-sts-tl-name").text("1小时"));
				break;
			//当时间间隔为15分钟时，默认3小时
			case 15:
				$tlabel.append($('<span>').attr("tmid",3).addClass("cafe-tl-sts-tl-name").text("3小时"));
				break;
			//当时间间隔为30分钟时，默认6小时
			case 30:
				$tlabel.append($('<span>').attr("tmid",6).addClass("cafe-tl-sts-tl-name").text("6小时"));
				break;
			//当时间间隔为1小时时，默认12小时
			case 1*60:
				$tlabel.append($('<span>').attr("tmid",12).addClass("cafe-tl-sts-tl-name").text("12小时"));
				break;
			 //当时间间隔为3小时时，默认24小时
			case 3*60:
				$tlabel.append($('<span>').attr("tmid",72).addClass("cafe-tl-sts-tl-name").text("72小时"));
				break;
			//当时间间隔为6小时时，默认72小时
			case 6*60:
				$tlabel.append($('<span>').attr("tmid",72).addClass("cafe-tl-sts-tl-name").text("72小时"));
				break;
			//当时间间隔为12或24小时时，默认7天
			case 12*60:
			case 24*60:
				$tlabel.append($('<span>').attr("tmid",7*24).addClass("cafe-tl-sts-tl-name").text("7天"));
				break;
		}
		$sts.append($tsel).append($tlabel);
		var $sta = $('<div>').addClass("cafe-tl-sta");
		var $ta = $('<div>').addClass("cafe-tl-sta-timearea");
		$ta.append($('<div>').addClass("cafe-tl-sta-t-tip").append($('<span>')))
		   .append($('<div>').addClass("cafe-tl-sta-t-slider"))
		   .append($('<div>').addClass("cafe-tl-sta-t-bg"))
		   .append($('<div>').addClass("cafe-tl-sta-t-defbg")); 
		var $tl = $('<div>').addClass("cafe-tl-sta-timelabel");
		$sta.append($ta).append($tl);
		$smooth.append($sts).append($sta);
		var $timeControl = $('<div>').addClass("cafe-tl-timecontrol");
		$timeControl.append($('<span>').addClass("cafe-tl-left-icon"))
					.append($('<span>').addClass("cafe-tl-play-icon"))
					.append($('<span>').addClass("cafe-tl-right-icon"))
					.append($('<span>').addClass("cafe-tl-speed").attr("speed",4).attr("animate",1).append($('<i>').text("慢")))
					.append($('<span>').addClass("cafe-tl-speed").attr("speed",2).attr("animate",1.5).append($('<i>').text("中")).addClass('active'))
					.append($('<span>').addClass("cafe-tl-speed").attr("speed",1).attr("animate",2).append($('<i>').text("快")));
        $timeControl.append($('<span>').addClass("cafe-tl-refresh-icon"));
		$time.append($scroll).append($smooth).append($timeControl);
	}
    function bulidTime2($time,timeArr){
        var $scroll = bulidScroll(timeArr);
        var $timeControl = $('<div>').addClass("cafe-tl-timecontrol style2");
        $timeControl.append($('<span>').addClass("cafe-tl-left-icon"))
            .append($('<span>').addClass("cafe-tl-right-icon"));
        $time.append($scroll).append($timeControl);
    }
	//创建时间序列
	function bulidScroll(timeArr){
		var $scroll = $('<section>');
		var scrollW = Math.floor((containerWidth - rightWidth + 1)/timeBtnW)*timeBtnW - 1;
		$scroll.addClass("cafe-tl-scroll").css("width",scrollW + "px").data("maxNum", Math.ceil(scrollW / timeBtnW));
		var $content = bulidScrollContent(timeArr);
		$scroll.append($content);
		return $scroll;
	}
	function bulidScrollContent(timeArr){
		var $content = $('<section>');
		$content.addClass("cafe-tl-content").css("width",(timeArr.length * timeBtnW - 1) + "px");
		var oldDay;
		for(var i = 0; i < timeArr.length; i++){
			var to = timeArr[i];
			var $i = $('<i>');
			var fullDate = new Date(to.fullTime);
			if(to.isdef){
				$i.addClass("active");
			}
			if(to.warnInfo){
				$i.addClass("alarm");
			}
			if(to.isgt24h){
				if(to.showTime.startsWith("01")){
					$i.attr("dateTip", fullDate.format("yyyy-M"));
				}
			}else{
				if (fullDate.getDate() != oldDay) {
					$i.attr("dateTip", fullDate.format("dd日"));
				}
				oldDay = fullDate.getDate();
				/*
				if(to.showTime.startsWith("00")){
					$i.attr("dateTip", fullDate.format("dd日"));
				}
				*/
			}
			if(to.isgt24h || to.showTime.endsWith("H")){
				$i.addClass("hh");
			}
			$i.addClass("cafe-tl-item tl-"+to.type).text(to.showTime).attr({"index" : i, "title" : to.fullTime}).data("timeObj",to);
			$content.append($i);
		}
		return $content;
	}
	/**
	 * 播放
	 */
	function play($drop,cfg){
		clearInterval($drop.find(".cafe-tl-play-icon").val());
		var interval = -1;
		if($drop.find(".cafe-tl-refresh-icon").hasClass("active")){
			var ti = $drop.find(".cafe-tl-sts-tl-name").attr("tmid") * 60;
			var bgW =  $drop.find(".cafe-tl-sta-t-defbg").width();
			var per = ti / bgW;
			var frameNumber = 60;
			var animate = Number($drop.find(".cafe-tl-speed.active").attr("animate")||1);
			var step = (parseFloat($drop.find(".cafe-tl-sta-timelabel>span:eq(1)").css("margin-left")) + 32) / frameNumber * animate;
			var avgss = 1000/frameNumber;
			
			
			var layerIds = [], timesArr = [] ;
			cfg.layers.forEach(function(layer){
				layerIds.push(layer.id);
			})
			var timeArr = getPlayDataTimeArr($drop, cfg.timeInterval);
			timeArr.forEach(function(time){
				timesArr.push(new Date(time).getTime());
			})

			interval = setInterval(function(){
				var $tip = $drop.find(".cafe-tl-sta-t-tip");
				var $slider = $drop.find(".cafe-tl-sta-t-slider");
				var sliderleft = parseFloat($slider.css("left")) + step;
				if(sliderleft >= bgW - 12){
					sliderleft = -12;
				}
				$slider.css("left", sliderleft + "px").siblings(".cafe-tl-sta-t-bg").css("width",(sliderleft + 12) + "px");
				var time = new Date($drop.find(".cafe-tl-sta-timelabel").find("span:first").attr("time"));
				time.setMinutes(time.getMinutes() + Math.round((sliderleft + 12) * per));
				$tip.css("left",(sliderleft - 52) + "px").find("span").text(time.format("hh:mm"));
								
				GIS.GridShow.animate(cfg.gisId,layerIds,timesArr,time.getTime());
			}, avgss);
		}else{
			var speed = $drop.find(".cafe-tl-speed.active").attr("speed");
			if(!speed){
				speed = 3;
			}
			interval = setInterval(function(){
				var $curItem = $drop.find(".cafe-tl-item.active");
				$curItem.removeClass("active");
				if($curItem.next().length > 0){
					$curItem.next().addClass("active").siblings().removeClass("active");
				}else{
					$curItem.siblings().first().addClass("active");
				}
				if($.isFunction(cfg.call)){
					if($("#c-b-layermanage .cafe-layer-body .cafe-layer-item").length === 0)return;
					cfg.call(cfg.pro);
				}
			},speed * 500);
		}
		
		$drop.find(".cafe-tl-play-icon").val(interval);
		$(cfg.appendTo).data('interval', interval);
	}
	/**
	 * 创建时长选择界面
	 */
	function bulidDuration(cfg){
		var $duration = $('<div>').addClass("cafe-tl-d-container");
		var $d1 = $('<div>').addClass("cafe-tl-d-line");
		var $d2 = $('<div>').addClass("cafe-tl-d-line");
		var $d3 = $('<div>').addClass("cafe-tl-d-line");
		switch(parseInt(cfg.timeInterval)){
			//当时间间隔为5或6分钟时，可选1/3/6/12/24/48/72小时
			case 5:
			case 6:
				$d1.append($('<span>').attr("sid",1).addClass("active").text("1h"))
				   .append($('<span>').attr("sid",3).text("3h"))
				   .append($('<span>').attr("sid",6).text("6h"));
				$d2.append($('<span>').attr("sid",12).text("12h"))
				   .append($('<span>').attr("sid",24).text("24h"));
				$d3.append($('<span>').attr("sid",48).text("48h"))
				   .append($('<span>').attr("sid",72).text("72h"));
				$duration.append($d1).append($d2).append($d3);
				break;
			//当时间间隔为10分钟时，可选2/3/6/12/24/48/72小时
			case 10:
				$d1.append($('<span>').attr("sid",1).text("1h"))
				   .append($('<span>').attr("sid",3).text("3h"))
				   .append($('<span>').attr("sid",6).addClass("active").text("6h"));
				$d2.append($('<span>').attr("sid",12).text("12h"))
				   .append($('<span>').attr("sid",24).text("24h"));
				$d3.append($('<span>').attr("sid",48).text("48h"))
				   .append($('<span>').attr("sid",72).text("72h"));
				$duration.append($d1).append($d2).append($d3);
				break;
			//当时间间隔为15分钟时，可选3/6/12/24/48/72小时
			case 15:
				$d1.append($('<span>').attr("sid",3).addClass("active").text("3h"))
				   .append($('<span>').attr("sid",6).text("6h"));
				$d2.append($('<span>').attr("sid",12).text("12h"))
				   .append($('<span>').attr("sid",24).text("24h"));
				$d3.append($('<span>').attr("sid",48).text("48h"))
				   .append($('<span>').attr("sid",72).text("72h"));
				$duration.append($d1).append($d2).append($d3);
				break;
			//当时间间隔为30分钟时，可选6/12/24/48/72小时
			case 30:
				$d1.append($('<span>').attr("sid",6).addClass("active").text("6h"))
				   .append($('<span>').attr("sid",12).text("12h"))
				   .append($('<span>').attr("sid",24).text("24h"));
				$d2.append($('<span>').attr("sid",48).text("48h"))
				   .append($('<span>').attr("sid",72).text("72h"));
				$duration.css("height","69px").append($d1).append($d2);
				break;
			//当时间间隔为1小时时，可选12/24/48/72小时
			case 1*60:
				$d1.append($('<span>').attr("sid",12).addClass("active").text("12h"))
				   .append($('<span>').attr("sid",24).text("24h"));
				$d2.append($('<span>').attr("sid",48).text("48h"))
				   .append($('<span>').attr("sid",72).text("72h"));
				$duration.css("height","69px").append($d1).append($d2);
				break;
			 //当时间间隔为3小时时，可选24/48/72小时
			case 3*60:
				$d1//.append($('<span>').attr("sid",24).text("24h"))
				   //.append($('<span>').attr("sid",48).text("48h"))
				   .append($('<span>').attr("sid",72).addClass("active").text("72h"));
				$duration.css("height","37px").append($d1);
				break;
			//当时间间隔为6小时时，可选72小时
			case 6*60:
				$d1.append($('<span>').attr("sid",72).addClass("active").text("72h"));
				$duration.css("height","37px").append($d1);
				break;
			//当时间间隔为12或24小时时，可选7天
			case 12*60:
			case 24*60:
				$d1.append($('<span>').attr("sid",7*24).addClass("active").text("7天"));
				$duration.css("height","37px").append($d1);
				break;
		}
		var $d4 = $('<div>').addClass("cafe-tl-d-sanjiao");
		$duration.append($d4);
		
		$duration.off().on("click",".cafe-tl-d-line>span",function(){
			if(!$(this).hasClass("active")){
				var $dc = $(this).closest(".cafe-tl-d-container");
				$dc.find(".cafe-tl-d-line>span").removeClass("active");
				$(this).addClass("active");
				$dc.siblings(".cafe-timeline").find(".cafe-tl-sts-tl-name").attr("tmid",$(this).attr("sid")).text($(this).attr("sid") + "小时");
				$dc.siblings(".cafe-timeline").find(".cafe-tl-sta-t-tip,.cafe-tl-sta-t-slider,.cafe-tl-sta-t-bg").removeAttr("style");
				var $play = $dc.siblings(".cafe-timeline").find(".cafe-tl-play-icon");
				if($play.hasClass("active")){
					$play.click();
				}
				bulidTimeLabel($dc.siblings(".cafe-timeline"),cfg,true);
			}
		});
		return $duration;
	}
	/**
	 * 创建时间刻度
	 */
	function bulidTimeLabel($drop,cfg,isShow){
		var $timelabel = $drop.find(".cafe-tl-sta-timelabel");
		$timelabel.empty();
		if(isShow){
			var curtime = new Date($drop.find(".cafe-tl-item.active").attr("title"));
			$drop.find(".cafe-tl-sta-t-tip>span").text(curtime.format("hh:mm"));
			var maxtime = new Date($drop.find(".cafe-tl-item.active").attr("title"));
			var duration = $drop.find(".cafe-tl-sts-tl-name").attr("tmid") * 60;
			var timeInterval = getSmoothti(duration,cfg.timeInterval)[0];
			maxtime.setMinutes(maxtime.getMinutes() + duration - timeInterval);
			var ml = $timelabel.siblings(".cafe-tl-sta-timearea").width() / ((duration - timeInterval) / timeInterval) - 32;
			$timelabel.append($('<span>').attr("time",curtime).text(curtime.format("hh:mm")));
			while (curtime.getTime() < maxtime.getTime()) {
				curtime.setMinutes(curtime.getMinutes() + timeInterval);
				var $span = $('<span>').attr("time",curtime).text(curtime.format("hh:mm"));
				$span.css("margin-left", ml + "px");
				$timelabel.append($span);
			}
			var time = getPlayDataTimeArr($drop, cfg.timeInterval);
			cfg.getPlayData(cfg.pro, time.join(","));
		}
	}
	//获取播放数据时间数组
	function getPlayDataTimeArr($drop, timeInterval){
		var curtime = new Date($drop.find(".cafe-tl-item.active").attr("title"));
		var maxtime = new Date($drop.find(".cafe-tl-item.active").attr("title"));
		var duration = $drop.find(".cafe-tl-sts-tl-name").attr("tmid") * 60;
		maxtime.setMinutes(maxtime.getMinutes() + duration);
		var dtimeInterval = getSmoothti(duration, timeInterval)[1];
		var timeArr = [];
		while (curtime.getTime() < maxtime.getTime()) {
			timeArr.push(curtime.format("yyyy-MM-dd hh:mm:ss"));
			curtime.setMinutes(curtime.getMinutes() + dtimeInterval);
		}
		return timeArr;
	}
	//平滑时间轴上时间刻度间隔和数据时间间隔
	function getSmoothti(t, timeInterval){
		timeInterval = timeInterval || 6;
		switch (parseInt(t)) {
			case 1*60:
				return [timeInterval,timeInterval];
			case 3*60:
				return [30,30];
			case 6*60:
				return [60,30];
			case 12*60:
				return [60,60];
			case 24*60:
				return [3*60,2*60];
			case 48*60:
				return [6*60,4*60];
			case 72*60:
				return [3*60,3*60];
			case 7*24*60:
				return [24*60,24*60];
		}
	}
	/**
	 * 绑定事件
	 */
	function _eves($drop,cfg){
		$drop.off().on("click",".cafe-tl-item",function(e){//选择时间
			e.stopPropagation();
			if(!$(this).hasClass("active")){
				$(this).addClass("active").siblings().removeClass("active");
				if(!cfg.iszcqfx && $("#c-b-layermanage .cafe-layer-body .cafe-layer-item").length === 0)return;
				if(1 == cfg.type || 2 == cfg.type){
					if(cfg.iszcqfx){
						cfg.pro.clickTime = new Date($(this).data("timeObj").fullTime+":00").getTime();
						cfg.call(cfg.pro);
					}else{
						if($.isFunction(cfg.call)){
							cfg.call(cfg.pro);
						}
					}
				}else{
					var $alarm = $drop.find(".cafe-tl-alarm-icon[time='"+$(this).attr("title")+"']");
					$alarm.find("span").each(function(){
						if(!$(this).hasClass("active")){
							$(this).trigger("click");
						}
					});
				}
			}
		}).on("click",".cafe-ic-xiangzuo4",function(){//向左移动
			var $curItem = $drop.find(".cafe-tl-item.active");
			var marginLeft = parseFloat($curItem.css("margin-left"));
			
			var $scroll = $(".cafe-tl-scroll");
			var maxNum = $(".cafe-tl-time .cafe-tl-scroll").data("maxNum");
			if(($curItem.position().left+marginLeft) < timeBtnW && $curItem.prev().length > 0){
				var $fill = $drop.find(".cafe-tl-a-fill").removeClass("sk lj dl");
				var nowActiveIndex = $(".cafe-timeline .cafe-tl-content .active").attr("index");
				var preNum =  Math.floor(($(".cafe-timeline .cafe-tl-content .active").position().left + 1)/timeBtnW)   //前面有几个
				
				if($curItem.prevAll().length >= maxNum){
					$fill.addClass($curItem.data("timeObj").type);
					$scroll.scrollLeft(($curItem.index() - maxNum)  * timeBtnW);
					
				}else{
					$fill.addClass($drop.find("i.cafe-tl-item:eq(" + maxNum + ")").data("timeObj").type);
					$scroll.scrollLeft(0);
				}
			}
			$curItem.prev().addClass("active").siblings().removeClass("active");
		}).on("click",".cafe-ic-xiangyou",function(){//向右移动
			var $curItem = $drop.find(".cafe-tl-item.active");
			var $scroll = $(".cafe-tl-scroll");
			var maxNum = $(".cafe-tl-time .cafe-tl-scroll").data("maxNum");
			if(maxNum == Math.ceil(($curItem.position().left + timeBtnW) / timeBtnW) && $curItem.next().length > 0){
				var $fill = $drop.find(".cafe-tl-a-fill").removeClass("sk lj dl");
				var nextAllNum = $curItem.nextAll().length;
				
				var len = $drop.find(".newDiv").length;
				var nowActiveIndex = $(".cafe-timeline .cafe-tl-content .active").attr("index");
				var preNum =  Math.floor(($(".cafe-timeline .cafe-tl-content .active").position().left + 1)/timeBtnW)   //前面有几个
				var lastIndex = $(".cafe-timeline .cafe-tl-content .cafe-tl-item:last").attr("index");
				var showLastIndex = (Number(maxNum)-preNum-1) + Number(nowActiveIndex);									//页面显示的最后一个index
				
				if(nextAllNum >= maxNum){
					$fill.addClass($drop.find("i.cafe-tl-item:eq(" + ($curItem.index() + maxNum) + ")").data("timeObj").type);
					$scroll.scrollLeft(($curItem.index() + 1)  * timeBtnW);
				}else{
					$fill.addClass($curItem.nextAll().last().data("timeObj").type);
					$scroll.scrollLeft($scroll.scrollLeft() + nextAllNum  * timeBtnW);
				}
			}
			$curItem.next().addClass("active").siblings().removeClass("active");
		}).on("click",".cafe-tl-left-icon",function(){//点击向左
			if($drop.find(".cafe-tl-refresh-icon").hasClass("active")){
				var $slider = $(".cafe-tl-sta-t-slider");
				var bgW =  $drop.find(".cafe-tl-sta-t-defbg").width();
				var $tip = $drop.find(".cafe-tl-sta-t-tip");
				var timeArr = getPlayDataTimeArr($drop, cfg.timeInterval);
				var duration = $drop.find(".cafe-tl-sts-tl-name").attr("tmid") * 60;
				var timeInterval = getSmoothti(duration, cfg.timeInterval)[1];
				var step = bgW / (duration / timeInterval - 1);
				var curLeft = parseFloat($slider.css("left")) - step;
				var index = Math.ceil(curLeft/step);
				if(curLeft <= -12){
					index = 0;
				}
                var curWidth = index * step;
				$slider.css("left",(curWidth - 12) + "px").siblings(".cafe-tl-sta-t-bg").css("width",curWidth + "px");
				var time = new Date(timeArr[index]);
				$tip.css("left",(curWidth - 64) + "px").find("span").text(time.format("hh:mm"));
				
				var layerIds = [], timesArr = [] ;
				cfg.layers.forEach(function(layer){
					layerIds.push(layer.id);
				})
				var timeArr = getPlayDataTimeArr($drop, cfg.timeInterval);
				timeArr.forEach(function(time){
					timesArr.push(new Date(time).getTime());
				})
				GIS.GridShow.animate(cfg.gisId,layerIds,timesArr,time.getTime());
				
			}else{
				var $curItem = $drop.find(".cafe-tl-item.active");
				if(0 == $curItem.prev().length){
					var curTime = new Date(cfg.curDate);
					curTime.setMinutes(curTime.getMinutes() + cfg.timeInterval);
					
					var prevTime = new Date($curItem.attr("title"));
					if (curTime.getTime() >= prevTime.getTime()) return;
					
					prevTime.setMinutes(prevTime.getMinutes());
					var timeArr = getTimeArr(prevTime, -cfg.timeInterval, cfg);
					timeArr.reverse();
					var $scrollContent = bulidScrollContent(timeArr);
					$drop.find(".cafe-tl-time .cafe-tl-scroll").empty().append($scrollContent);
				}else{
					$curItem.prev().addClass("active").siblings().removeClass("active");
				}
				if($.isFunction(cfg.call)){
					if($("#c-b-layermanage .cafe-layer-body .cafe-layer-item").length === 0)return;
					cfg.call(cfg.pro);
				}
			}
		}).on("click",".cafe-tl-play-icon",function(e){//点击播放
			e.stopPropagation();
			if($(this).hasClass("active")){
				if(GLMap.getLayer('boundaryLayerId')){
					GLMap.getLayer('boundaryLayerId').visible=true;
				}
				$(this).removeClass("active");
				$(this).find("i.cafe-ifont").remove();
				clearInterval($(this).val());
			}else{
				if(GLMap.getLayer('boundaryLayerId')){
					GLMap.getLayer('boundaryLayerId').visible=false;
				}
				$(this).addClass("active");
				//$(this).append($('<i>').addClass("cafe-ifont cafe-ic-zanting"));
				play($drop,cfg);
			}
		}).on("click",".cafe-tl-right-icon",function(){//点击向右
			if($drop.find(".cafe-tl-refresh-icon").hasClass("active")){
				var $slider = $(".cafe-tl-sta-t-slider");
				var bgW =  $drop.find(".cafe-tl-sta-t-defbg").width();
				var $tip = $drop.find(".cafe-tl-sta-t-tip");
				var timeArr = getPlayDataTimeArr($drop, cfg.timeInterval);
				var duration = $drop.find(".cafe-tl-sts-tl-name").attr("tmid") * 60;
				var timeInterval = getSmoothti(duration, cfg.timeInterval)[1];
				var step = bgW / (duration / timeInterval - 1);
				var curLeft = parseFloat($slider.css("left")) + step;
				var index = Math.ceil(curLeft/step);
				if(curLeft >= bgW - 12){
					index = timeArr.length - 1;
				}
				var curWidth = index * step;
				$slider.css("left",(curWidth - 12) + "px").siblings(".cafe-tl-sta-t-bg").css("width",curWidth + "px");
				var time = new Date(timeArr[index]);
				$tip.css("left",(curWidth - 64) + "px").find("span").text(time.format("hh:mm"));
				
				var layerIds = [], timesArr = [] ;
				cfg.layers.forEach(function(layer){
					layerIds.push(layer.id);
				})
				var timeArr = getPlayDataTimeArr($drop, cfg.timeInterval);
				timeArr.forEach(function(time){
					timesArr.push(new Date(time).getTime());
				})
				GIS.GridShow.animate(cfg.gisId,layerIds,timesArr,time.getTime());
			}else{
				var $curItem = $drop.find(".cafe-tl-item.active");
				if(0 == $curItem.next().length){
					var nextTime = new Date($curItem.attr("title"));
					var maxtime = new Date(cfg.curDate);
					maxtime.setMinutes(maxtime.getMinutes() + cfg.maxHour * 60);
					if(nextTime.getTime() < maxtime.getTime()){
						var timeArr = getTimeArr(nextTime, cfg.timeInterval, cfg);
						var $scrollContent = bulidScrollContent(timeArr);
						$drop.find(".cafe-tl-time .cafe-tl-scroll").empty().append($scrollContent);
					}
				}else{
					$curItem.next().addClass("active").siblings().removeClass("active");
				}
				if($.isFunction(cfg.call)){
					if (cfg.iszcqfx) {
						cfg.call(cfg.pro);
					} else {
						if($("#c-b-layermanage .cafe-layer-body .cafe-layer-item").length === 0)return;
						cfg.call(cfg.pro);
					}
				}
			}
		}).on("click",".cafe-tl-speed",function(){//选择播放速度
			if($(this).hasClass("active")){
				$(this).removeClass("active");
			}else{
				$(this).addClass("active").siblings(".cafe-tl-speed").removeClass("active");
			}
			if($(this).siblings(".cafe-tl-play-icon").hasClass("active")){
				play($drop,cfg);
			}
		}).on("click",".cafe-tl-refresh-icon",function(){//切换时间轴展示方式
			var $tc = $drop.find(".cafe-tl-timecontrol");
			if($(this).hasClass("active")){
				var $play = $drop.find(".cafe-tl-play-icon");
				if($play.hasClass("active")){
					$play.click();
				}
				$(this).removeClass("active");
				$tc.removeClass("smooth");
				$drop.siblings(".cafe-tl-d-container").hide();
				$drop.find(".cafe-tl-duration").removeClass("active").hide();
				$drop.find(".cafe-tl-smooth").hide();
				$drop.find(".cafe-tl-scroll,.cafe-tl-speed,.cafe-tl-thumbnail-icon").show();
				$drop.find(".cafe-tl-sta-t-tip,.cafe-tl-sta-t-slider,.cafe-tl-sta-t-bg").removeAttr("style");
				
				var layerIds = [], timesArr = [] ;
				cfg.layers.forEach(function(layer){
					layerIds.push(layer.id);
				})
				var timeArr = getPlayDataTimeArr($drop, cfg.timeInterval);
				timeArr.forEach(function(time){
					timesArr.push(new Date(time).getTime());
				})
				
				GIS.GridShow.animate(cfg.gisId,layerIds,timesArr,new Date($drop.find(".cafe-tl-item.active").attr("title")).getTime());
			}else{
				$(this).addClass("active");
				$tc.addClass("smooth");
				$drop.find(".cafe-tl-scroll,.cafe-tl-speed,.cafe-tl-thumbnail-icon").hide();
				$drop.find(".cafe-tl-duration").show();
				$drop.find(".cafe-tl-smooth").show();
			}
			$drop.find(".cafe-tl-smooth").css("width",(containerWidth - $tc.width()) + "px");
			$drop.find(".cafe-tl-smooth>.cafe-tl-sta").css("width",(containerWidth - $tc.width() - 80) + "px");
			bulidTimeLabel($drop,cfg,$(this).hasClass("active"));
		}).on("click",".cafe-tl-thumbnail-icon",function(){//打开缩略图
			if($(this).hasClass("active")){
				$(this).removeClass("active");
				$drop.siblings(".cafe-tl-thumbnail").slideUp(150);
			}else{
                //bulidThumbnail($drop,cfg);
                $(this).addClass("active");
                $drop.siblings(".cafe-tl-thumbnail").slideDown(150);
			}
		}).on("click",".cafe-tl-duration",function(){//显示时长选择
			if($(this).hasClass("active")){
				$(this).removeClass("active");
				$drop.siblings(".cafe-tl-d-container").hide();
			}else{
				$(this).addClass("active");
				if(!$drop.siblings(".cafe-tl-d-container").is(":hidden")){
					$drop.before(bulidDuration(cfg));
				}else{
					$drop.siblings(".cafe-tl-d-container").show();
				}
			}
		}).on("mousedown",".cafe-tl-sta-t-slider",function(event){//拖动滑块
			var left = parseFloat($(this).css("left"));
			var that = this;
			var ti = $drop.find(".cafe-tl-sts-tl-name").attr("tmid") * 60;
			var bgW =  $(this).siblings(".cafe-tl-sta-t-defbg").width();
			var per = ti / bgW;
			
			var layerIds = [], timesArr = [] ;
			cfg.layers.forEach(function(layer){
				layerIds.push(layer.id);
			})
			var timeArr = getPlayDataTimeArr($drop, cfg.timeInterval);
			timeArr.forEach(function(time){
				timesArr.push(new Date(time).getTime());
			})
			window.document.onmousemove = function(ev){
				ev.preventDefault();
				var step = 1;
				var $tip = $(that).siblings(".cafe-tl-sta-t-tip");
				var offset = ev.pageX-event.pageX;
				var _left = left + Math.round(offset / step) * step;
				if(_left <= -12){
					_left = -12;
				}else if(_left >= bgW - 12){
					_left = bgW - 12;
				}
				$(that).css("left",_left + "px").siblings(".cafe-tl-sta-t-bg").css("width",(_left + 12) + "px");
				var time = new Date($drop.find(".cafe-tl-sta-timelabel").find("span:first").attr("time"));
				time.setMinutes(time.getMinutes() + Math.round((_left + 12) * per));
				$tip.css("left",(_left - 52) + "px").find("span").text(time.format("hh:mm"));
				
				GIS.GridShow.animate(cfg.gisId,layerIds,timesArr,time.getTime());
			};
			window.document.onmouseup = function(){
				window.document.onmousemove = null;
				window.document.onmouseup = null;
			};
		});
	}
	//是否查询数据
	function isQueryData(ctime, cfg){
		var curTime = new Date(cfg.curDate);
		var clickTime = new Date(ctime);
		if(curTime.getTime() != clickTime.getTime()){
			return true;
		}
		return false;
	}
	
	var timeBtnW = 41;//单个时间按钮宽度
	var containerWidth = 0;//容器的宽度
	var rightWidth = 61;//右侧部分宽度
	var timeBtnNum = 41;//默认显示时间个数
	var CFTimeline = function(settings){
		var options = {
				appendTo: null,//控件所在容器
				curDate: null,//控件上的时间
				gisId : null,//gis的ID
				getLayers : null,//获取层次数组
				getHisData : null,//触发实况历史数据查询
				timeInterval : 180,//时间间隔，单位分钟，默认5分钟
				type : null,//时间轴风格
				maxHour: 240, // 最大预报时间
				call : null,//控件点击事件
				closeFun : null,//关闭控件事件
				lockFun : null,//点击‘锁’触发的事件
				containerWidth : null //容器宽度
		};
		this.config = $.extend({},options);
		if(1 == settings.type){
			rightWidth = 189+25;
		}else if(2 == settings.type){
            rightWidth = 74;
            timeBtnNum = 44;
		}else{
			rightWidth = 59;
		}
		this.init(settings);
	}
	
	CFTimeline.prototype = {
		init : function(settings){
			this.config = $.extend(this.config, settings);
			if(!this.config.curDate){
				this.config.curDate = new Date();
			}else{
				this.config.curDate = new Date(this.config.curDate);
			}
			this.config.curDate = this.config.curDate.format("yyyy-MM-dd hh:mm");
			var $container = $(this.config.appendTo);
			if(this.config.containerWidth){
				containerWidth = this.config.containerWidth;
			}else{
				containerWidth = $container.width();
			}
			this.$drop = bulidHtml(this.config);
			_eves(this.$drop,this.config);

			if(this.config.appendTo){
				var isHide = $container.is(":hidden");
				$container.show().empty().append(this.$drop);
				if(!this.config.type){
					var $scroll = $container.find(".cafe-tl-scroll");
					var $scrollContent = $container.find(".cafe-tl-content");
					var total = Math.floor($scrollContent.width()/$scroll.width()) - 1;
					var offset = $scrollContent.width()%$scroll.width();
					$container.find(".cafe-tl-scroll").scrollLeft($scroll.width()  * total + offset);
					$container.find(".cafe-tl-a-fill").addClass("dl");
				}
				var that = this;
				$container.resize(function(){
					that.resize();
				});
				if(isHide){
					$container.hide();
				}
				that.resize();
			}
			this.destroy();
		},
		show : function(){
			this.$drop.parent().show();
			this.resize();
		},
		hide : function(){
			this.$drop.parent().hide();
			if($.isFunction(cfg.closeFun)){
				cfg.closeFun();
			}
		},
		remove : function(){
			this.$drop.empty();
		},
		getCurTime : function(){
			return this.$drop.find(".cafe-tl-item.active").attr("title");
		},
		getLastTime : function(){
            return this.$drop.find(".cafe-tl-item:last").attr("title");
		},
		setSelTime : function(time){
            this.$drop.find(".cafe-tl-item[title='"+time+"']").addClass("active").siblings().removeClass("active");
		},
		resize : function(){
			containerWidth = this.$drop.parent().width();
			var scrollW = Math.floor((containerWidth - rightWidth + 1)/timeBtnW)*timeBtnW - 1;
			var maxNum = Math.ceil(scrollW / timeBtnW);
			this.$drop.find(".cafe-tl-scroll").css("width",scrollW + "px").data("maxNum", maxNum);
			//this.$drop.find(".cafe-tl-scroll").scrollLeft(this.$drop.find(".cafe-tl-scroll")[0].scrollWidth);
		},
		isPlay : function(){
			return this.$drop.find(".cafe-tl-play-icon").hasClass("active");
		},
		updatePlayData : function(){
			if(this.$drop.find(".cafe-tl-refresh-icon").hasClass("active")){
				var time = getPlayDataTimeArr(this.$drop, this.config.timeInterval);
				var playData = this.config.getPlayData(this.config.pro, time.join(","));
				this.$drop.find(".cafe-tl-smooth").data("playData",playData);
			}
		},
		destroy : function(){
			//清除定时器
			clearInterval(this.$drop.find(".cafe-tl-play-icon").val());
			clearInterval($(this.config.appendTo).data('interval'));
		}
	};
	
	CafeJS.Timeline2 = function(settings){
		var drop =new CFTimeline(settings);
		return drop;
	}
});